﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Threading;
using FirstFloor.ModernUI.Presentation;
using LEShortcut.Helper;

namespace LEShortcut.Models.Views
{
    public class MainWindowViewModel
    {
        private readonly BackgroundWorker _worker = new BackgroundWorker();

        public MainWindowViewModel()
        {
            Context = new MainWindowViewContext();
            InitContext();
            InitBackgroundWorker();
        }

        public MainWindowViewContext Context { get; set; }

        private void InitContext()
        {
            Context.MenuLinkGroups = new LinkGroupCollection {new LinkGroup {DisplayName = "MainTitle".GetI18NString()}};
            Context.TitleLinks = new LinkCollection
            {
                new Link
                {
                    DisplayName = "Home".GetI18NString(),
                    Source = new Uri("Pages/Home.xaml", UriKind.Relative)
                },
                new Link
                {
                    DisplayName = "Setting".GetI18NString(),
                    Source = new Uri("Pages/Setting.xaml", UriKind.Relative)
                }
            };
        }

        private void AddLinkToMenuLinkGroups(Link link)
        {
            Context.MenuLinkGroups[0].Links.Add(link);
        }

        private void InitBackgroundWorker()
        {
            _worker.DoWork += BackgroundWoker_CheckUpdate;
            _worker.RunWorkerAsync();
        }

        private void BackgroundWoker_CheckUpdate(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var version = new Version();
            var cache = Application.Current.Resources["cache"] as AppCache;
            Debug.Assert(cache != null, "cache != null");
            cache.IsNewVersion = UpdateHelper.CheckUpdate(ref version);
            if (cache.IsNewVersion)
            {
                Dispatcher dispatcher = Application.Current.Dispatcher;
                dispatcher.Invoke(new AddLinkToMenuLinkGroupsEvent(AddLinkToMenuLinkGroups),
                    new Link
                    {
                        DisplayName = string.Format("NewVerFound".GetI18NString(), version),
                        Source = new Uri("Pages/Update.xaml", UriKind.Relative)
                    });
            }
        }

        private delegate void AddLinkToMenuLinkGroupsEvent(Link link);
    }
}